<template>
  <div class="hot-topic-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>热点事件管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加事件
        </el-button>
        <el-button type="warning" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 实时监控面板 -->
    <div class="monitoring-panel">
      <div class="panel-header">
        <h3>实时监控</h3>
        <div class="status-indicator">
          <div class="indicator-dot active"></div>
          <span>监控中</span>
        </div>
      </div>
      
      <div class="monitoring-stats">
        <div class="stat-card urgent">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ monitoringStats.urgent }}</div>
            <div class="stat-label">紧急事件</div>
          </div>
        </div>
        <div class="stat-card trending">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ monitoringStats.trending }}</div>
            <div class="stat-label">热点事件</div>
          </div>
        </div>
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ monitoringStats.total }}</div>
            <div class="stat-label">总监控事件</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <el-form :model="searchForm" inline>
        <el-form-item label="事件标题">
          <el-input v-model="searchForm.title" placeholder="请输入事件标题" clearable />
        </el-form-item>
        <el-form-item label="事件类型">
          <el-select v-model="searchForm.type" placeholder="请选择事件类型" clearable>
            <el-option label="诈骗事件" value="fraud" />
            <el-option label="谣言事件" value="rumor" />
            <el-option label="网络攻击" value="cyber_attack" />
            <el-option label="数据泄露" value="data_leak" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-select v-model="searchForm.urgency" placeholder="请选择紧急程度" clearable>
            <el-option label="紧急" value="urgent" />
            <el-option label="重要" value="important" />
            <el-option label="一般" value="normal" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="监控中" value="monitoring" />
            <el-option label="处理中" value="handling" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 事件列表 -->
    <div class="event-list">
      <el-table :data="eventList" v-loading="loading" stripe>
        <el-table-column label="事件标题" min-width="250">
          <template #default="{ row }">
            <div class="event-title">
              <span>{{ row.title }}</span>
              <el-tag v-if="row.isHot" type="danger" size="small">🔥 热点</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事件类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getUrgencyColor(row.urgency)">
              {{ getUrgencyLabel(row.urgency) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="热度值" width="100">
          <template #default="{ row }">
            <div class="heat-value">{{ row.heatValue }}</div>
          </template>
        </el-table-column>
        <el-table-column label="影响范围" width="120">
          <template #default="{ row }">
            <span>{{ row.affectedUsers }}人</span>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发现时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.discoveredAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewEvent(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status !== 'completed'"
              type="warning" 
              size="small" 
              @click="handleEvent(row)"
            >
              处理
            </el-button>
            <el-dropdown @command="handleAction">
              <el-button type="info" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'toggleHot', row}">
                    {{ row.isHot ? '取消热点' : '标记热点' }}
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'escalate', row}">
                    升级处理
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'archive', row}">
                    归档事件
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 添加事件对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加热点事件"
      width="700px"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventFormRules"
        label-width="120px"
      >
        <el-form-item label="事件标题" prop="title">
          <el-input v-model="eventForm.title" placeholder="请输入事件标题" />
        </el-form-item>
        <el-form-item label="事件类型" prop="type">
          <el-select v-model="eventForm.type" placeholder="请选择事件类型">
            <el-option label="诈骗事件" value="fraud" />
            <el-option label="谣言事件" value="rumor" />
            <el-option label="网络攻击" value="cyber_attack" />
            <el-option label="数据泄露" value="data_leak" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgency">
          <el-select v-model="eventForm.urgency" placeholder="请选择紧急程度">
            <el-option label="紧急" value="urgent" />
            <el-option label="重要" value="important" />
            <el-option label="一般" value="normal" />
          </el-select>
        </el-form-item>
        <el-form-item label="影响范围" prop="affectedUsers">
          <el-input-number
            v-model="eventForm.affectedUsers"
            :min="0"
            placeholder="请输入影响用户数"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="事件描述" prop="description">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入详细的事件描述"
          />
        </el-form-item>
        <el-form-item label="处理措施" prop="handlingMeasures">
          <el-input
            v-model="eventForm.handlingMeasures"
            type="textarea"
            :rows="3"
            placeholder="请输入处理措施"
          />
        </el-form-item>
        <el-form-item label="是否热点">
          <el-switch v-model="eventForm.isHot" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvent" :loading="submitting">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 事件详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="事件详情"
      width="800px"
    >
      <div class="event-detail" v-if="selectedEvent">
        <div class="detail-header">
          <h3>{{ selectedEvent.title }}</h3>
          <div class="detail-badges">
            <el-tag :type="getTypeColor(selectedEvent.type)">
              {{ getTypeLabel(selectedEvent.type) }}
            </el-tag>
            <el-tag :type="getUrgencyColor(selectedEvent.urgency)">
              {{ getUrgencyLabel(selectedEvent.urgency) }}
            </el-tag>
            <el-tag v-if="selectedEvent.isHot" type="danger">🔥 热点</el-tag>
          </div>
        </div>

        <div class="detail-stats">
          <div class="stat-item">
            <span class="label">热度值：</span>
            <span class="value">{{ selectedEvent.heatValue }}</span>
          </div>
          <div class="stat-item">
            <span class="label">影响范围：</span>
            <span class="value">{{ selectedEvent.affectedUsers }}人</span>
          </div>
          <div class="stat-item">
            <span class="label">发现时间：</span>
            <span class="value">{{ formatDate(selectedEvent.discoveredAt) }}</span>
          </div>
        </div>

        <div class="detail-content">
          <div class="content-section">
            <h4>事件描述</h4>
            <p>{{ selectedEvent.description }}</p>
          </div>

          <div class="content-section">
            <h4>处理措施</h4>
            <p>{{ selectedEvent.handlingMeasures || '暂无处理措施' }}</p>
          </div>

          <div class="content-section">
            <h4>处理时间线</h4>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-dot"></div>
                <div class="timeline-content">
                  <div class="timeline-title">事件发现</div>
                  <div class="timeline-time">{{ formatDate(selectedEvent.discoveredAt) }}</div>
                </div>
              </div>
              <div class="timeline-item" v-if="selectedEvent.handledAt">
                <div class="timeline-dot"></div>
                <div class="timeline-content">
                  <div class="timeline-title">开始处理</div>
                  <div class="timeline-time">{{ formatDate(selectedEvent.handledAt) }}</div>
                </div>
              </div>
              <div class="timeline-item" v-if="selectedEvent.completedAt">
                <div class="timeline-dot"></div>
                <div class="timeline-content">
                  <div class="timeline-title">处理完成</div>
                  <div class="timeline-time">{{ formatDate(selectedEvent.completedAt) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 处理事件对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="处理事件"
      width="600px"
    >
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        :rules="handleFormRules"
        label-width="120px"
      >
        <el-form-item label="处理措施" prop="measures">
          <el-input
            v-model="handleForm.measures"
            type="textarea"
            :rows="4"
            placeholder="请输入具体的处理措施"
          />
        </el-form-item>
        <el-form-item label="预计完成时间" prop="expectedTime">
          <el-date-picker
            v-model="handleForm.expectedTime"
            type="datetime"
            placeholder="选择预计完成时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="assignee">
          <el-input v-model="handleForm.assignee" placeholder="请输入负责人" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle" :loading="submitting">
            开始处理
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Refresh, Warning, TrendCharts, DataAnalysis, 
  Search, ArrowDown 
} from '@element-plus/icons-vue'

// 数据状态
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 表单引用
const eventFormRef = ref(null)
const handleFormRef = ref(null)

// 实时监控统计
const monitoringStats = reactive({
  urgent: 3,
  trending: 12,
  total: 67
})

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  urgency: '',
  status: ''
})

// 选中的事件
const selectedEvent = ref(null)

// 事件表单
const eventForm = reactive({
  title: '',
  type: '',
  urgency: '',
  affectedUsers: 0,
  description: '',
  handlingMeasures: '',
  isHot: false
})

// 处理表单
const handleForm = reactive({
  measures: '',
  expectedTime: '',
  assignee: ''
})

// 表单验证规则
const eventFormRules = {
  title: [
    { required: true, message: '请输入事件标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择事件类型', trigger: 'change' }
  ],
  urgency: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入事件描述', trigger: 'blur' }
  ]
}

const handleFormRules = {
  measures: [
    { required: true, message: '请输入处理措施', trigger: 'blur' }
  ],
  assignee: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

// 模拟事件数据
const eventList = ref([
  {
    id: 1,
    title: '大规模电信诈骗团伙活动异常',
    type: 'fraud',
    urgency: 'urgent',
    heatValue: 856,
    affectedUsers: 1234,
    status: 'handling',
    isHot: true,
    discoveredAt: '2024-01-15T10:30:00',
    handledAt: '2024-01-15T11:00:00',
    description: '监测到某地区电信诈骗活动异常增加...',
    handlingMeasures: '已启动紧急响应机制，联系相关部门协同处理'
  },
  {
    id: 2,
    title: '虚假投资平台谣言传播',
    type: 'rumor',
    urgency: 'important',
    heatValue: 432,
    affectedUsers: 567,
    status: 'monitoring',
    isHot: false,
    discoveredAt: '2024-01-14T14:20:00',
    description: '发现关于某投资平台的不实信息大量传播...',
    handlingMeasures: ''
  }
])

// 方法
const loadEvents = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    total.value = eventList.value.length
  } catch (error) {
    ElMessage.error('加载事件失败')
  } finally {
    loading.value = false
  }
}

const search = () => {
  currentPage.value = 1
  loadEvents()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    type: '',
    urgency: '',
    status: ''
  })
  search()
}

const refreshData = () => {
  loadEvents()
  ElMessage.success('数据刷新成功')
}

const showAddDialog = () => {
  resetEventForm()
  dialogVisible.value = true
}

const viewEvent = (row) => {
  selectedEvent.value = row
  detailDialogVisible.value = true
}

const handleEvent = (row) => {
  selectedEvent.value = row
  resetHandleForm()
  handleDialogVisible.value = true
}

const resetEventForm = () => {
  Object.assign(eventForm, {
    title: '',
    type: '',
    urgency: '',
    affectedUsers: 0,
    description: '',
    handlingMeasures: '',
    isHot: false
  })
}

const resetHandleForm = () => {
  Object.assign(handleForm, {
    measures: '',
    expectedTime: '',
    assignee: ''
  })
}

const submitEvent = async () => {
  if (!eventFormRef.value) return

  try {
    await eventFormRef.value.validate()
    submitting.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    const newEvent = {
      ...eventForm,
      id: Date.now(),
      heatValue: Math.floor(Math.random() * 1000),
      status: 'monitoring',
      discoveredAt: new Date().toISOString()
    }
    eventList.value.unshift(newEvent)
    
    ElMessage.success('事件添加成功')
    dialogVisible.value = false
    loadEvents()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const submitHandle = async () => {
  if (!handleFormRef.value) return

  try {
    await handleFormRef.value.validate()
    submitting.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    if (selectedEvent.value) {
      selectedEvent.value.status = 'handling'
      selectedEvent.value.handledAt = new Date().toISOString()
      selectedEvent.value.handlingMeasures = handleForm.measures
    }

    ElMessage.success('处理任务创建成功')
    handleDialogVisible.value = false
    loadEvents()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleCloseDialog = () => {
  dialogVisible.value = false
  resetEventForm()
}

const handleAction = async ({ action, row }) => {
  switch (action) {
    case 'toggleHot':
      row.isHot = !row.isHot
      ElMessage.success(row.isHot ? '已标记为热点' : '已取消热点')
      break
    case 'escalate':
      ElMessage.success('事件已升级处理')
      break
    case 'archive':
      ElMessage.success('事件已归档')
      break
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadEvents()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadEvents()
}

// 辅助函数
const getTypeLabel = (type) => {
  const labels = {
    fraud: '诈骗事件',
    rumor: '谣言事件',
    cyber_attack: '网络攻击',
    data_leak: '数据泄露',
    other: '其他'
  }
  return labels[type] || type
}

const getTypeColor = (type) => {
  const colors = {
    fraud: 'danger',
    rumor: 'warning',
    cyber_attack: 'danger',
    data_leak: 'warning',
    other: 'info'
  }
  return colors[type] || ''
}

const getUrgencyLabel = (urgency) => {
  const labels = {
    urgent: '紧急',
    important: '重要',
    normal: '一般'
  }
  return labels[urgency] || urgency
}

const getUrgencyColor = (urgency) => {
  const colors = {
    urgent: 'danger',
    important: 'warning',
    normal: 'success'
  }
  return colors[urgency] || ''
}

const getStatusLabel = (status) => {
  const labels = {
    monitoring: '监控中',
    handling: '处理中',
    completed: '已完成'
  }
  return labels[status] || status
}

const getStatusColor = (status) => {
  const colors = {
    monitoring: 'info',
    handling: 'warning',
    completed: 'success'
  }
  return colors[status] || ''
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadEvents()
})
</script>

<style scoped>
.hot-topic-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.monitoring-panel {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h3 {
  margin: 0;
  color: #333;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #67c23a;
}

.indicator-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #67c23a;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.monitoring-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card.urgent {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.stat-card.trending {
  background: linear-gradient(135deg, #f39c12 0%, #d35400 100%);
}

.stat-card.total {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
}

.stat-icon {
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.search-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.event-list {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.event-title {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.heat-value {
  font-weight: bold;
  color: #e74c3c;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.event-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-header h3 {
  margin: 0;
  color: #333;
  flex: 1;
}

.detail-badges {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.detail-stats {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-item .label {
  color: #666;
  font-weight: bold;
}

.stat-item .value {
  color: #333;
}

.content-section {
  margin-bottom: 20px;
}

.content-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.content-section p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #e6e6e6;
}

.timeline-item {
  position: relative;
  margin-bottom: 20px;
}

.timeline-dot {
  position: absolute;
  left: -16px;
  top: 4px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #409eff;
  border: 2px solid white;
  box-shadow: 0 0 0 2px #409eff;
}

.timeline-content {
  padding-left: 10px;
}

.timeline-title {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.timeline-time {
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .hot-topic-management {
    padding: 10px;
  }
  
  .monitoring-stats {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .detail-stats {
    flex-direction: column;
    gap: 15px;
  }
}
</style> 